<template>
  <div class="box1">
    <el-div v-if="addBoxStatus">
      <!-- addBoxStatus -->
      <el-form :rules="rules" :model="form">
        <el-form-item label="🦔" :label-width="formLabelWidth">
          <div style="width: 50%">
            <input-image class="AddImg" v-model="form.avatar" />
          </div>
        </el-form-item>
        <el-form-item
          label="商品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            v-model="form.name"
            autocomplete="off"
            maxlength="61"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="商品价格"
          :label-width="formLabelWidth"
          prop="price"
        >
          <el-input
            v-model="form.price"
            autocomplete="off"
            type="number"
            oninput="if(value.length>9)value=value.slice(0,9)"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="商品分类"
          :label-width="formLabelWidth"
          prop="classify_id"
        >
          <el-select
            v-model="form.classify_id"
            filterable
            placeholder="商品类型"
          >
            <el-option
              v-for="item in classify"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="商品简介"
          :label-width="formLabelWidth"
          prop="label"
        >
          <el-input
            v-model="form.label"
            autocomplete="off"
            autosize
            type="textarea"
            maxlength="256"
            label
          ></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer">
        <el-button type="primary" @click="goodsAdd"> 确认 </el-button>
      </span>
    </el-div>
    <!-- 提示框 -->
    <el-div v-if="addCompleteStatus" :sm="12" :lg="6">
      <el-result
        icon="success"
        title="添加成功"
        sub-title="Please follow the instructions"
      >
        <template #extra>
          <el-button type="primary" size="medium" @click="addJump()"
            >返回首页</el-button
          >
        </template>
      </el-result>
    </el-div>
  </div>
</template>

<script>
import { onBeforeMount, ref, reactive } from "vue";
import InputImage from "./InputImage.vue";
import { goodsApi, goodsAddApi, classifyApi } from "@/api/goods";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
export default {
  components: {
    InputImage,
  },
  setup() {
    const router = useRouter();
    let tableData = ref([]);
    const classify = reactive([]);
    const addBoxStatus = ref(true);
    const addCompleteStatus = ref(false);
    // 防抖函数
    function debounce(fn) {
      let timer = null;
      return function () {
        if (timer != null) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          fn();
        }, 250);
      };
    }
    // const debounce = (fn) => {
    //   let timer = null;
    //   return function () {
    //     if (timer != null) {
    //       clearTimeout(timer);
    //     }
    //     timer = setTimeout(() => {
    //       fn();
    //     }, 500);
    //   };
    // };
    // 获取上架商品数据&获取商品分类数据
    onBeforeMount(async () => {
      await goodsApi().then((res) => {
        tableData.value.push(...res.data.query.goods_stock);
        console.log(res);
      });
      await classifyApi().then((res) => {
        const data = res.data.query.result.map((item) => {
          item.validity == "1"
            ? (item.validity = true)
            : (item.validity = false);
          return item;
        });
        Object.assign(classify, data);
      });
    });
    // 定义表单初始值
    let form = reactive({
      name: null,
      price: null,
      classify_id: null,
      index: null,
      label: null,
      avatar: null,
    });
    // 声明变量用来接收对应商品
    const data = reactive({
      goods_id: "",
      state: "",
    });
    const edit = reactive({
      goods_id: "",
      state: "",
      name: "",
      price: "",
      label: "",
      classify_id: "",
    });
    // 获取对应商品的数据并赋值
    const handleGoodsAdd = (row) => {
      data.goods_id = row.id;
      data.state = row.state;
    };
    const handleGoodsEdit = (index, row) => {
      edit.goods_id = row.id;
      edit.state = row.state;
      edit.name = row.name;
      edit.price = row.price;
      edit.label = row.label;
      edit.index = index;
      edit.classify_id = row.classify_id;
      goodsIndex = index;
    };
    // 添加商品操作
    const goodsAdd = debounce(() => {
      // 通过formData格式向服务器端发送数据
      const formData = new FormData();
      // 处理文件上传表单项
      Object.entries(form).forEach(([k, v]) => {
        if (k == "avatar") {
          if (v) formData.append(k, v, v.name);
        } else formData.append(k, v);
      });
      if (
        form.name == null ||
        form.price == null ||
        form.classify_id == null ||
        form.label == null ||
        form.avatar == null
      ) {
        ElMessage.error("商品信息填写不全,请填写完成后提交.");
      } else if (form.price <= 0) {
        ElMessage.error("商品价格需要大于0！");
      } else {
        goodsAddApi(formData).then((res) => {
          if (res.data.success) {
            // centerDialogVisible.value = true;
            addCompleteStatus.value = true;
            addBoxStatus.value = false;
            form.value = reactive({
              name: null,
              price: null,
              classify_id: null,
              index: null,
              label: null,
              avatar: null,
            });
            console.log(form.value);
          }
        });
      }
    });
    // 跳转添加页面
    const addJump = () => {
      router.push("/dashboard");
      // path: '/goodsAdd.vue'
    };
    return {
      form,
      edit,
      classify,
      handleGoodsAdd,
      handleGoodsEdit,
      goodsAdd,
      // centerDialogVisible,
      addBoxStatus,
      addCompleteStatus,
      addJump,
      debounce,
      rules: {
        name: [
          { required: true, message: "输入的商品名称不能为空" },
          { min: 1, max: 60, message: "商品名称不能超过60个字段" },
        ],
        price: [
          { required: true, message: "输入的商品价格不能为空" },
          { min: 1, max: 8, message: "商品价格不能超过8位" },
        ],
        classify_id: [{ required: true, message: "输入的商品分类不能为空" }],
        label: [
          { required: true, message: "输入的商品描述不能为空" },
          { min: 1, max: 255, message: "商品描述不能超过255个字段" },
        ],
      },
    };
  },
};
</script>
<style scoped>
.AddImg {
  width: 30%;
  height: 30%;
  margin-left: 10px;
  display: inline-block;
}
.box1 {
  width: 75%;
  height: 100%;
  overflow-y: hidden;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  margin: auto;
  margin-top: 20px;
  margin-bottom: 1.5rem;
  border-radius: 4px;
  min-height: 36px;
  padding: 20px;
}
</style>
